package com.diandi.activity.controller;

import com.alibaba.fastjson.JSON;
import com.diandi.activity.DateFormatUtils;
import com.diandi.activity.bean.Activity;
import com.diandi.activity.bean.RewardPointType;
import com.diandi.activity.service.ActivityWebService;
import com.diandi.ddsb.bean.Result;
import com.diandi.ddsb.bean.Results;
import com.diandi.ddsb.vo.Constant;
import com.diandi.ddsb.vo.InvestActStasticsInfoVo;
import com.diandi.ddsb.vo.NewActivityInfoVo;
import com.diandi.utils.NumberUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by a on 2018/3/20.
 */
@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityWebService activityWebService;
    private static Logger logger = LoggerFactory.getLogger(ActivityController.class);
    /**
     * 投资活动---新
     */
    @RequestMapping("/investNewActivityIndex")
    public ModelAndView investNewActivityIndex() {
        logger.info("访问活动管理首页");
        return new  ModelAndView("activity/investNewActivityIndex");
    }
    /**
     * 返回活动列表数据
     *
     * @return
     */
    @RequestMapping(value = "/queryActivitys")
    public String queryActivitys(@RequestParam(required = false) Long id, @RequestParam(required = false) String title,
                                 @RequestParam(required = false) Integer rewardPoint, @RequestParam(required = false) Integer status,
                                 @RequestParam(required = false) Integer publishPlatform,
                                 @RequestParam(required = false) String createStartTime,
                                 @RequestParam(required = false) String createEndTime, @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "20") int rows, String points) {
        int from = (page - 1) * rows;
        Map<String, Object> paramMap = getParamMap(status);
        paramMap.put("id", id);
        paramMap.put("title", title);
        paramMap.put("from", from);
        paramMap.put("rows", rows);
        if (rewardPoint == null && StringUtils.isBlank(points)) {
            paramMap.put("rewardPoints", "rewardPoints");
            paramMap.put("publishPlatforms", publishPlatform);
        } else if (!StringUtils.isBlank(points)) {
            paramMap.put("points", NumberUtil.getTicketIds(points));
        } else {
            paramMap.put("rewardPoint", rewardPoint);
            if (rewardPoint == RewardPointType.invest_send_hb.getValue()
                    || rewardPoint == RewardPointType.LUCK_DRAW.getValue()
                    || rewardPoint == RewardPointType.TOTAL_INVEST_ACTIVITY.getValue()
                    || rewardPoint == RewardPointType.MJ_TURN_TABLE.getValue()) {
                paramMap.put("publishPlatforms", publishPlatform);
            } else {
                paramMap.put("publishPlatforms", publishPlatform);
            }
        }

        if (StringUtils.isNotBlank(createStartTime)) {
            paramMap.put("createStartTime", DateFormatUtils.reverseDate(createStartTime + " 00:00:00"));
        }
        if (StringUtils.isNotBlank(createEndTime)) {
            paramMap.put("createEndTime", DateFormatUtils.reverseDate(createEndTime + " 23:59:59"));
        }

        List<Activity> activitys = activityWebService.queryActivitys(paramMap);
        Integer count = activityWebService.queryActivitysCount(paramMap);
        Map dataGridJsonData = new HashMap();
        dataGridJsonData.put("total", count);
        dataGridJsonData.put("rows", activitys);
        return JSON.toJSONString(dataGridJsonData);
    }
    private Map<String, Object> getParamMap(Integer status) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (status != null) {
            if (status == 0) {// 未开始
                map.put("WKS", "WKS");
            } else if (status == 1) {// 进行中
                map.put("JXZ", "JXZ");
            } else if (status == 2) {// 已结束
                map.put("YJS", "YJS");
            }
        }
        return map;
    }
    /**
     * 投资活动(新)新建页面
     */
    @RequestMapping("/addInvestNewActivityIndex")
    public ModelAndView goAddInvestNewActivityIndex() {
        logger.info("访问新建投资活动(新)页面");
        return new  ModelAndView("activity/addInvestNewActivityIndex");
    }
    /**
     * 新建活动保存按钮
     */
    @RequestMapping("/addNewInvestActivity")
    public Object addNewInvestActivity(NewActivityInfoVo activity) {
        Results result = new Results();
        try {
            Long staffId = 1l;
            activity.setStaffId(staffId);
            System.out.println(activity.getRuleList().get(0).getRewardPointInRule());
            result = activityWebService.addNewInvestActivity(activity);
        } catch (RuntimeException ex) {
            ex.printStackTrace();
            result.setCode(Constant.FAIL);
            result.setMsg(ex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("activitController[method]" + e.getMessage());
            result.setCode(Constant.FAIL);
            result.setMsg("新增活动失败" + e.getMessage());
        }
        return JSON.toJSONString(result);
    }
    /**
     * 查看活动详细信息
     */
    @RequestMapping(value = "/activityDetail")
    public ModelAndView activityDetail( Long id,  String editFlag) throws Exception {
        Map<String,Object> map =  activityWebService.getDetailMV(id, editFlag);
        ModelAndView modelAndView = new ModelAndView(map.get("viewName").toString());
        map.remove("viewName");
        modelAndView.addAllObjects(map);
        return modelAndView;
    }
    /**
     * 更新活动信息回显
     */
    @RequestMapping(value = "/updateActivity", produces = "text/plain;charset=UTF-8")
    public String updateActivity(Activity activity) {
        Result result = new Result();
        try {
            result = activityWebService.updateActivity(activity);
        } catch (Exception e) {
            result.setCode(Constant.FAIL);
            result.setMsg(e.getMessage());
        }
        return JSON.toJSONString(result);
    }

    /**
     *
     * 投资活动统计
     *
     * @param id
     * @return ModelAndView
     * @author liuxu
     * @since 2016年12月30日
     */
    @RequestMapping(value = "/investActStatisIndex")
    public ModelAndView investActStatisIndex(@RequestParam(required = true) Long id) {
        ModelAndView mv = new ModelAndView();

        Map<String, Object> data = activityWebService.queryActivityInfoForStatistics(id);
        mv.addObject("id", id);
        mv.addAllObjects(data);
        mv.setViewName("activity/investActivityStatisticsIndex");
        return mv;
    }

    @RequestMapping(value = "/queryInvestActInfo")
    public Object queryInvestActInfo(@RequestParam(required = true) Long activityId,
                                     @RequestParam(required = false) Integer borrowTypes, @RequestParam(required = false) Integer publishPlats,
                                     @RequestParam(required = false) Long ticketId, @RequestParam(required = false) String userPhone,
                                     @RequestParam(required = false) Long userId, @RequestParam(required = false) Long investAmountPeriod,
                                     @RequestParam(required = false) Long investMonthPeriod, @RequestParam(required = false) Integer ticketType,
                                     @RequestParam(required = false) String createStartTime,
                                     @RequestParam(required = false) String createEndTime, @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "20") Integer rows) {
        int from = (page - 1) * rows;
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("activityId", activityId);
        condition.put("borrowTypes", borrowTypes);
        condition.put("publishPlats", publishPlats);
        condition.put("ticketId", ticketId);
        condition.put("userPhone", userPhone);
        condition.put("userId", userId);
        condition.put("investAmountPeriod", investAmountPeriod);
        condition.put("investMonthPeriod", investMonthPeriod);
        condition.put("ticketType", ticketType);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(createStartTime)) {
            condition.put("createStartTime", DateFormatUtils.reverseDate(createStartTime));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(createEndTime)) {
            condition.put("createEndTime", DateFormatUtils.reverseDate(createEndTime));
        }
        condition.put("from", from);
        condition.put("rows", rows);

        List<InvestActStasticsInfoVo> list = activityWebService.queryInvestStatisticsInfoByCondition(condition);
        Integer total = activityWebService.queryInvestStatisticsInfoCountByCondition(condition);

        Map<String, Object> dataGridJsonData = new HashMap<String, Object>();

        dataGridJsonData.put("total", null == total ? 0 : total);
        dataGridJsonData.put("rows", list);

        return JSON.toJSON(dataGridJsonData);
    }


}
